var express = require('express');
const mysql = require("mysql");
var file = require('fs')
const zhaopin = express();
const jwt = require('jsonwebtoken');

//设置跨域访问
zhaopin.all('*', function (req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers', '*')
  res.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS');
  res.header('Content-Type', 'application/json;charset=utf-8');
  next()
});

var connsql = mysql.createConnection({
  host: 'localhost',
  port: '3306',
  user: 'root',
  password: 'root',
  database: 'zhaopin' // 数据库
})
connsql.connect() // 开启与数据库连接
console.log("数据库连接成功")

//接受传递过来的参数
const bodyParser = require('body-parser');
zhaopin.use(bodyParser.urlencoded({ extended: false }));
zhaopin.use(bodyParser.json());


zhaopin.post('/register', function (req, res) {
  var selsql = "select * from user where username ='" + req.body.username + "'"
  var regsql = "INSERT INTO `user` (`username`, `password`,`email`) VALUES ('" + req.body.username + "','" + req.body.password + "','" + req.body.email + "')";
  connsql.query(selsql, (err, result) => {
    if (err) {
      console.log(err);
      return
    }
    if (result == "") {
      connsql.query(regsql, (err, result) => {
        if (err) {
          console.log(err);
          return
        }
        res.json({ code: 1, msg: "注册成功" })
      })
    } else {
      res.json({ code: -1, msg: "用户名重复" })
    }
  })
});







zhaopin.post('/login', function (req, res) {
  var czsql = "select * from user where username ='" + req.body.username + "'"
  connsql.query(czsql, (err, result) => {
    if (err) {
      console.log(err);
      return
    }
    let username = result[0].username
    let token = jwt.sign({
      username,
      id: result[0].id
    }, "secretkey")
    res.send({ code: 1, token, username })
  })
})



module.exports = zhaopin;
zhaopin.listen(3082, () => {
  console.log("启动3082");
})